<template>
  <div class="article-list">
    <!-- 文章表格 -->
     <h1 style="margin: 0px 0px 40px 80px;">资讯列表</h1>
     <span>标题</span>
     <input type="text" placeholder="请输入标题搜索" v-model="searchText" class="search-input">
     <span>创建时间</span>
    <input type="date" v-model="createDate" />

      <a href="#" class="addNews" @click.prevent="goToPage(1)">搜索</a>
     <a href="#" class="addNews" style="float: right;" @click.prevent="addNews()" v-if="type==1">添加资讯</a>
    <table border="1" cellpadding="8" cellspacing="0" width="100%">
      <thead>
        <tr>
          <th>资讯标题</th>
          <th>创建时间</th>
          <th v-if="type==1">操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(news, index) in newsPageInfo.list" :key="index" >
          <td> <a href="#" @click.prevent="toNewsDetail(news)">{{ news.title }}</a></td>
          <td>{{ news.createTime }}</td>
          <td style="width: 10%;" v-if="type==1">
            <a href="#" style="margin-right: 20px;" @click.prevent="updateNews(news.id)">修改</a>
            <a href="#" @click.prevent="delNews(news.id)">删除</a>
          </td>
        </tr>
        <tr v-if="newsPageInfo.list && newsPageInfo.list.length === 0">
          <td colspan="2">暂无数据</td>
        </tr>
      </tbody>
    </table>

    <!-- 分页控件 -->
    <div class="pagination" style="margin-top: 10px; text-align: right;" v-if="newsPageInfo.list.length !== 0">
      <span style="margin-right: 20px;">当前第 {{ newsPageInfo.pageNum }} 页，共 {{ newsPageInfo.pages }} 页，总记录数 {{ newsPageInfo.total }} 条</span>
      <button @click="goToPage(1)" :disabled="newsPageInfo.pageNum === 1">首页</button>
      <button @click="goToPage(newsPageInfo.pageNum - 1)" :disabled="newsPageInfo.pageNum === 1">上一页</button>
      <span v-for="n in newsPageInfo.navigatepageNums" :key="n">
        <button @click="goToPage(n)" :disabled="newsPageInfo.pageNum === n">{{ n }}</button>
      </span>
      <button @click="goToPage(newsPageInfo.pageNum + 1)" :disabled="newsPageInfo.pageNum === newsPageInfo.pages">下一页</button>
      <button @click="goToPage(newsPageInfo.pages)" :disabled="newsPageInfo.pageNum === newsPageInfo.pages">尾页</button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted,watch } from 'vue';
import { useRouter } from 'vue-router'
import axios from 'axios'// 导入axios库

const searchText = ref('');
const createDate = ref('');

const router = useRouter()

const type =  ref(2);
const storedType = sessionStorage.getItem("type");
if (storedType!=null) {
    type.value = storedType;
}

// 分页方法
const goToPage = (page) => {
  if (page >= 1 && page <= newsPageInfo.value.pages) {
    newsPageInfo.value.pageNum = page;
    fetchNews();
  }
};

const newsPageInfo = ref({// 创建响应式数据newsPageInfo，用于存储从后端获取的PageInfo<News>对象
  list: [],        // 新闻列表
  pageNum: 1,      // 当前页码
  pageSize: 10,    // 每页大小
  total: 0,        // 总记录数
  pages: 1,        // 总页数
  navigatepageNums: [1] ,// 导航页码
})

const fetchNews = async () => {
    try{
        const response = await axios.post('/api/pageNews',{//必填pageNum,pageSize,得到pageInfo
            pageNum:newsPageInfo.value.pageNum,
            pageSize:newsPageInfo.value.pageSize,
            title:searchText.value,
            createTime:createDate.value
        })
        newsPageInfo.value = response.data;
        if(newsPageInfo.value.list.length == 0){
          newsPageInfo.value.pages = 1;
        }

        console.log(newsPageInfo.value);
        
    }catch(error){
        console.error('获取数据失败:', error)
    }
}

// 当组件挂载完成后执行fetchNews函数，获取后端数据
onMounted(() => {
  fetchNews();
})
// 监听路由变化并重新获取数据
watch(
  () => router.currentRoute.value,
  (to, from) => {
    if (to.path === '/newsList') {
      fetchNews();
    }
  }
);
//修改
function updateNews(id){
router.push({
  name: 'updateNews',
  query: {
    id: id
  }
})
}

//资讯详情
function toNewsDetail(news) {
  router.push({
    name: 'newsDetail',
    query: { 
      title: news.title,
      content: news.content,
      createTime: news.createTime
    }
  })
}
//删除资讯
const deletNews = async (id) => {
    try{
        const response = await axios.get('/api/deleteNews?id='+id)
        alert("删除成功！");
        fetchNews();
    }catch(error){
        alert('删除失败！');
   
    }
}
//删除
function delNews(id)  {
console.log("del",id)
if(confirm("确定删除吗？")){
   deletNews(id);
   
}
}
//添加
function addNews(){
router.push({
  name: 'addNews',
})
}

</script>

<style scoped>

button {
  cursor: pointer;
  border: 1px solid #ccc;
  background: transparent;
  padding: 2px 8px;
  margin: 0 3px;
}

button:disabled {
  cursor: not-allowed;
  opacity: 0.6;
}
.addNews{
  margin:10px;
  padding:0 10px;
  border: 1px solid #555555;
}
</style>
